<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;
use OT\DataDictionary;
use User\Api\UserApi;
//use QL\QueryList;
//use QL\Ext\PhantomJs;
/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class IndexController extends HomeController {

  //系统首页
    public function index(){

//        $category = D('Category')->getTree();
//
//        //echo '<pre>';var_dump($category);die;
//        $lists    = D('Document')->lists(null);
//
//        $this->assign('category',$category);//栏目
//        $this->assign('lists',$lists);//列表
//        $this->assign('page',D('Document')->page);//分页
//
//
//        $this->display();
        header("Location:".U('/Home/Article/lists/category/tuijian'));
    }

    static function pa($url=''){

        //Vendor('Querylist.autoload');
        
        // 1 新浪新闻详情页
        // $data = \QL\QueryList::get('http://news.sina.com.cn/zx/2018-01-10/doc-ifyqkarr8341130.shtml')
        //     // 设置采集规则
        //     ->rules([
        //         'title'=>array('.main-title','text'),
        //         'video'=>array('#article', 'text'),
        //         'link'=>array('#article','html')
        //     ])
        //     ->query()->getData();

        // 2 人民网国际新闻
        // $data = \QL\QueryList::get('http://world.people.com.cn/')->encoding('UTF-8','GB2312')
        //     // 设置采集规则
        //     ->rules([
        //         'title'=>array('a','text'),
        //         'a'=>array('a','href'),
        //         'img'=>array('img','src')
        //     ])->removeHead()->range('ul>li')->query()->getData();

        //3 搜狐新闻旅游详情
        // $data = \QL\QueryList::get('http://www.sohu.com/a/215854010_498659?_f=index_chan29news_2')
        //     // 设置采集规则
        //     ->rules([
        //         'title'=>array('h1','text'),
        //         'create_time'=>array('#news-time','text'),
        //         'description'=>array('p:eq(1)','text'),
        //         'content'=>array('#mp-editor','html'),
               
        //     ])->query()->getData();

        // $map = $data->all();
        // $map[0]['source'] = '搜狐新闻';
        // $sql = D('Document')->add($map[0]);
        
        $html = self::pa_article($url);

        if(empty($html)){
            $html = self::pa_section($url);

        }
        return $html;

    }

    static function pa_article($url){
        $ql = \QL\QueryList::get($url);
           
        $data = $ql->find('.art_content')->htmls();

        $html = $data->all();
        return $html[0];
    }

    static function pa_section($url){
        $ql = \QL\QueryList::get($url);
           $rules = [
                'content' => ['.art_box','html','-h1 -section  -a']
            ];
        $data = $ql->rules($rules)->query();

        $data = $ql->getData();
        //var_dump($data);die;
        return $data[0]['content'];
    }

    public function pa_s_card(){
        $ql = \QL\QueryList::get('https://photo.sina.cn/album_4_704_263302.htm?cre=tianyi&mod=went&loc=9&r=0&doct=0&rfunc=18&tj=none&tr=12&vt=4&pos=12&hd=1');
           $rules = [
                'content' => ['article','html','-h1']
            ];
        $data = $ql->rules($rules)->query();

        $data = $ql->getData();
        var_dump($data);die;
        return $data[0]['content'];
    }

    public function set_rule(){

        $res = M('rules')->where('status=1')->order('RAND()')->limit(3)->select();

        foreach ($res as $k => $v) {
          $html =file_get_contents($v['url']);

          $data_html = json_decode($html,true) ;
          
          //$data = $data_html->data;
          $from_data = explode(',', $v['from_data']);
          $to_data = explode(',', $v['to_data']);
          foreach ($data_html['data'] as $key => $value) {
              for ($i=0; $i < count($from_data); $i++) { 
                  $map[$to_data[$i]] = $value[$from_data[$i]];
              }
              $article_url = $value[$v['article_url']];
              if ($article_url) {
                $map['content'] = self::pa($article_url);
              }

              $map['category_id'] = $v['category_id'];
              
                try {

                      D('Document')->add($map);
                  } catch (\Exception $e) {
                      echo 'Message: ' .$e->getMessage();continue;
                  }
              
              
          }
            
        }
        echo 'finished!';die;
         
    }

    public function pa_s(){
        $arr = array(
            'http://v2.sohu.com/public-api/feed?scene=CHANNEL&sceneId=8&page=2&size=200&callback=%20&_=1516176216987'
        );
         $json = file_get_contents($arr[array_rand($arr)]);
         $data = json_decode($json,true);
         //$html = $re['data'];

        //echo $html;

        //echo '<pre>';var_dump($data);//var_dump($username);
        foreach ($data as $k => $v){

                $uid = self::addname($v['authorName'],'123456','123@qq.com','','http:'.$v['authorPic']);
                //echo $username[$k];
                if($uid){
                    $map['type'] = 0;
                    $map['user_id'] = $uid;
                    //http://m.sohu.com/a/217191765_255783
                    $map['title'] = $v['title'];
                    //D('community')->add($map);
                    if(!D('community')->where($map)->select()){
                        $map['content'] = self::pa_content('http://m.sohu.com/a/'.$v['id'].'_'.$v['authorId']);
                        $map['created_at'] = $v['publicTime']/100;
                        $map['logos'] = serialize(array(ltrim($v['picUrl'],'//')));
                        try{
                            D('community')->add($map);
                        }catch (\Exception $e){}
                    }
                }


        }
        echo 'finished！';

    }

    static function pa_content($url){
        //WB_editor_iframe
        $ql = \QL\QueryList::get($url);

        $data = $ql->find('#articleContent')->htmls();

        $html = $data->all();

        //$f = file_get_contents($url);
        //echo $f;
        //var_dump($html);
        return $html[0];

    }

    static function addname($username = '', $password = '', $email = '',$mobile = '',$logo = ''){
            /* 调用注册接口注册用户 */
            $User   =   new UserApi;

            try{
                $uid    =   $User->register($username, $password, $email,$mobile,$logo);
                //$uid = M('Ucenter_member')->add(array('username'=>$username,'avatar'=>$logo));
                //var_dump($uid);
                if(0 < $uid){ //注册成功
                    $user = array('uid' => $uid, 'nickname' => $username, 'status' => 1);
                    M('Member')->add($user);
                }
            }catch (\Exception $e){

            }
            if($uid == -3){
                $user = $User->info($username,true);
                if($user){
                    return $user[0];
                }
            }

            //echo $uid;die;
            return $uid;
    }

    public function pa_zazhi(){
        $url = 'http://travel.163.com/special/';
        $zazhis = array(
            array('code'=>'dryou','name'=>'Dr.YOU','count'=>3,'rule'=>array('#endText','html','-.dr_history'),'charset'=>'GB2312'),
            array('code'=>'citystyle','name'=>'城市生活家','count'=>2,'rule'=>array('.left_content','html','-div'),'charset'=>'GBK'),
            array('code'=>'travelist','name'=>'月游榜','count'=>1,'rule'=>array('.contxt_1','html','-.tuji'),'charset'=>'GBK'),
            array('code'=>'travelogue','name'=>'说旅游','count'=>1,'rule'=>array('.tt_main_para','html'),'charset'=>'GBK'),
        );

//        $encode = mb_detect_encoding(file_get_contents('http://travel.163.com/special/yueyou2014110/'), array("ASCII",'UTF-8',"GB2312","GBK",'BIG5'));
//        //echo $encode;die;
//        $ql = \QL\QueryList::get('http://travel.163.com/special/yueyou2014110/');
//        $rules = [
//            'content' => ['.contxt_1','html','-.tuji']
//        ];
//        $data = $ql->rules($rules)->encoding('UTF-8','gb2312')->query();
//
//        $data = $data->getData();
//        echo '<pre>';var_dump($data);die;
//        return $data[0]['content'];

        foreach ($zazhis as $k => $v){
            for($i=$v['count'];$i>=1;$i--){
                $u = ($i == 1)?$url.$v['code']:$url.$v['code']."_0$i";
                $ql = \QL\QueryList::get($u);
                $rules = [
                    'img_url' => ['li>a>img','src'],
                    'title' =>['li>a>img','alt'],
                    'url' => ['li>span>a','href']
                ];
                $data = $ql->rules($rules)->encoding('UTF-8','gb2132')->query();

                $data = $ql->getData();
//                echo '<pre>';var_dump($data);die;
//                return $data[0]['content'];
                for($j=count($data)-1;$j>=0;$j--){
                    $map['title'] = $data[$j]['title'];
                    $map['code'] = $v['code'];
                    $map['magazine_name'] = $v['name'];
                    $map['rule'] = serialize($v['rule']);
                    $map['logo'] = $data[$j]['img_url'];
                    $map['url'] = $data[$j]['url'];
                    $map['charset'] = $v['charset'];
                    try{
                        D('Magazine')->add($map);
                    }catch (\Exception $e){
                        echo  $e->getMessage();
                        continue;
                    }
                }
            }
        }
    }

    public function update_zazhi_content(){
        $result = D('Magazine')->where('status = 0')->order('id asc')->limit(5)->select();
        if($result){
            foreach ($result as $k => $v){
                $ql = \QL\QueryList::get($v['url']);
                $rules = [
                    'content' => unserialize($v['rule'])
                ];
                $charset = empty($v['charset'])?'gbk':$v['charset'];
                $data = $ql->rules($rules)->encoding('UTF-8',$charset)->query();

                $data = $ql->getData();

                $content ='';
                foreach ($data as $key => $value){
                    $content .= $value['content'];
                }
                //echo $content;die;
                if($content){//$User->where('id=5')->save($data);
                    if(!M('Magazine')->where('id ='.$v['id'])->save(array('content'=>$content,'status'=>1))){
                        M('Magazine')->where('id ='.$v['id'])->delete();
                        echo '删除一个<br/>';
                    }
                }else{
                    M('Magazine')->where('id ='.$v['id'])->delete();
                    echo '删除一个<br/>';
                }
            }
        }
    }

}